//
//  UIDeviceAdditions.m
//  Tint
//
//  Created by Kevin Wu on 3/8/12.
//  Copyright (c) 2012 Telligenty. All rights reserved.
//

#import "UIDeviceAdditions.h"
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import "TTCore.h"
#import "NSStringAdditions.h"


@implementation UIDevice (Tint)


#pragma mark - Unique identifier

- (NSString *)MACAddress {
    
    int mib[6];
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        TTDERROR(@"if_nametoindex error");
        return nil;
    }
    
    size_t len;
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        TTDERROR(@"sysctl, take 1");
        return nil;
    }
    
    char *buf = malloc(len);
    if (buf == NULL) {
        TTDERROR(@"Could not allocate memory");
        return nil;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        TTDERROR(@"sysctl, take 2");
        free(buf);
        return nil;
    }
    
    struct if_msghdr *ifm = (struct if_msghdr *)buf;
    struct sockaddr_dl *sdl = (struct sockaddr_dl *)(ifm + 1);
    unsigned char *ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    
    return outstring;
}

- (NSString *)uniqueDeviceIdentifier {
    NSString *MACAddress = [self MACAddress];
    NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
    
    NSString *stringToHash = [NSString stringWithFormat:@"%@%@", MACAddress, bundleIdentifier];
    return [[stringToHash md5Hash] uppercaseString];
}

- (NSString *)uniqueGlobalDeviceIdentifier {
    NSString *MACAddress = [self MACAddress];
    return [[MACAddress md5Hash] uppercaseString];
}

@end
